#include "TLB.h"

using namespace std;

void insertEntry(TLB* tlb, int tick, long newPage, int newFrame) {
  // Check if TLB is full
  bool full = true;
  for (int i = 0; i < K; i++) {
    if (tlb->entries[i].page == -1) {
      // Empty entry -> fill it
      full = false;
      tlb->entries[i].page = newPage;
      tlb->entries[i].frame = newFrame;
      tlb->entries[i].tick = tick;
      break;
    }
  }

  if (full) { // TLB is full
    // Select entry to replace
    int oldestEntry = 0;
    for (int i = 1; i < K; i++) {
      if (tlb->entries[i].tick < tlb->entries[oldestEntry].tick) {
	oldestEntry = i;
      }
    }
    // Replace oldest entry with new translation
    tlb->entries[oldestEntry].page = newPage;
    tlb->entries[oldestEntry].frame = newFrame;
    tlb->entries[oldestEntry].tick = tick;
  }
}

void printTLB(TLB* tlb) {
  cout << endl << "TLB:" << endl;
  cout << "Page\tFrame\tTick" << endl << "--------------------" << endl;
  for (int i = 0; i < K; i++) {
    cout << tlb->entries[i].page << "\t";
    cout << tlb->entries[i].frame << "\t";
    cout << tlb->entries[i].tick << endl;
  }
  cout << endl;
}
